package com.tuanzi.loan.web.bean.system;

import static com.tuanzi.loan.business.constants.DictionaryCode.*;

import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.entity.system.Schedule;
import com.tuanzi.loan.business.service.system.ScheduleService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.request.system.ScheduleSearchRequest;
import com.tuanzi.loan.vo.response.system.ScheduleSearchResponse;
import com.tuanzi.loan.web.configuration.JSFListingBean;
import com.tuanzi.loan.web.lazy.system.ScheduleLazyDataModel;

import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * @author Ray 2017/09/21
 */
@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class ScheduleDefinitionListBean extends JSFListingBean<ScheduleSearchRequest, ScheduleSearchResponse> {

	private static final long serialVersionUID = -2152778554108785342L;

	@Autowired
	private ScheduleService scheduleService;

	@PostConstruct
	private void init() {
		initLazyDataModel();
	}

	public void onReset() {
		initLazyDataModel();
	}

	public String onAdd() {
		return redirect("/views/system/schedule/definition/info.xhtml");
	}

	public String onEdit(String id) {
		return redirect("/views/system/schedule/definition/info?id=" + id);
	}

	public void onBatchDisable() {
		scheduleService.disable(getSelectedSchedules());
		addSuccessfullyMessage();
	}

	public void onBatchEnable() {
		scheduleService.enable(getSelectedSchedules());
		addSuccessfullyMessage();
	}

	public void onDisable(String id) {
		scheduleService.disable(scheduleService.findOne(id));
		addSuccessfullyMessage();
	}

	public void onEnable(String id) {
		scheduleService.enable(scheduleService.findOne(id));
		addSuccessfullyMessage();
	}

	private List<Schedule> getSelectedSchedules() {
		return scheduleService.findAll(selectedRecords.parallelStream().map(ScheduleSearchResponse::getId).map(x -> x.toString()).collect(Collectors.toList()));
	}

	private void initLazyDataModel() {
		$ = new ScheduleSearchRequest();
		lazyDataModel = new ScheduleLazyDataModel($);
	}

	@Override
	protected List<String> getDictionaryCodes() {
		return Lists.newArrayList(SCHEDULE_START_TYPE, SCHEDULE_EXECUTE_TYPE, SCHEDULE_TASK_GROUP);
	}
}
